<?php

// liblogin.php by Matt Fritz
// April 13, 2010
// Controls login and authentication functions

require_once("database.php"); // require the database connection once

$loggedInURL = "index.php"; // where the user should be returned upon login
$logoutURL = "index.php"; // where the user should be returned upon logout

//error handler function
function customError($errno, $errstr, $errfile, $errline)
  {
  echo "<b>Error:</b> [$errno] $errstr ($errfile : line $errline)<br />";
  }

//set error handler
set_error_handler("customError");

// figure out whether a user is logged-in
function isLoggedIn()
{
	if(!empty($_SESSION['username']))
	{
		// a username exists, so the user is logged-in
		return true;
	}
	
	// no username exists, so the user is not logged-in
	return false;
}

// get the logged-in URL
function getLoggedInURL()
{
	global $loggedInURL;
	return $loggedInURL;
}

// get the username
function getUsername()
{
	return $_SESSION['username'];
}

// get the user type
function getUserType()
{
	return $_SESSION['userType'];
}

// return a message displaying whether the user is logged in or not
function getLoggedInMessage()
{
	$message = "";
	
	if(isLoggedIn())
	{
		// the user is logged-in
		$message = "You are logged-in as " . getUsername() . " (" . getUserType() . "). Go to:&nbsp;";
		$message .= "<div style='float:right'><form method='post' action='process.php' id='tasksForm'>";
		$message .= "<input type='hidden' name='formName' value='tasksForm' />";
		$message .= "<select id='tasksSelect' name='tasksSelect' onchange='if(document.getElementById(\"tasksSelect\").value != \"\") document.getElementById(\"tasksForm\").submit();'>";
		$message .= "<option value='' selected='selected'>(select a page)</option>";
		$message .= "<option value=''></option>";
		$message .= "<option value='assigncourses'>Assign Courses</option>";
		$message .= "<option value='managecourses'>Manage Courses</option>";
		$message .= "<option value='logout'>Logout</option>";
		$message .= "</select>";
		$message .= "</form></div>";
	}
	else
	{
		// the user is not logged-in
		$message = "You are not currently logged in. <a href='login.php'>Login</a> or <a href='register.php'>register</a>.";
	}
	
	return $message;
}

// create the fixed menu that floats on the upper-right hand corner of the screen
function createFixedMenu()
{
	return "<span id='menu' style='position:fixed;top:0px;right:0px;padding:2px;height:23px;background-color:#D8ECFB;border:1px solid black'>" . getLoggedInMessage() . "</span>";
}

// figure out whether a user is an administrator
function isAdmin()
{
	if(!empty($_SESSION['userType']))
	{
		if($_SESSION['userType'] == "Admin")
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	return false;
}

// figure out whether a user is a faculty member
function isFaculty()
{
	if(!empty($_SESSION['userType']))
	{
		if($_SESSION['userType'] == "Faculty")
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	return false;
}

// process a login request given a username and password combination
function processLogin($username, $password)
{
	// build the SELECT query for this user
	$loginQuery = getEncryptedLoginSQL($username, $password);
	
	// perform the query
	$loginResult = mysql_query($loginQuery);
	
	// check to see if results were returned
	if(mysql_num_rows($loginResult) > 0)
	{
		// this was a valid login, so grab the first result as an associative array
		$row = mysql_fetch_assoc($loginResult);
		
		// set the session variables from the returned query result
		$_SESSION['username'] = $row['username'];
		$_SESSION['userType'] = $row['type'];
		$_SESSION['firstName'] = $row['firstName'];
		$_SESSION['lastName'] = $row['lastName'];
		
		// return true to show that the login was successful
		return true;
	}
	
	// no user was found
	return false;
}

// process a logout request
function processLogout()
{
	// Unset all of the session variables.
    $_SESSION = array();

    // If it's desired to kill the session, also delete the session cookie.
    // Note: This will destroy the session, and not just the session data!
    if (isset($_COOKIE[session_name()])) {
    	setcookie(session_name(), '', time()-42000, '/');
    }

	session_unset();
	session_destroy();
	
	// re-direct to the desired logout URL
	global $logoutURL;
	print Header("Location: " . $logoutURL);
}

?>